/**
 * Created by kevin on 16/8/16.
 */
var eosi = window.eosi || {};
this.eosi.fotile = this.eosi.fotile || {};
//this.eosi.fotile = this.eosi.fotile || {};
//this.eosi.fotile = function(name) {
//    this.name = name;
//};

(function (window) {
    // the application
    function VideoPublicLeft(master) {
        this.Container_constructor();
        this.version = master.version;
        this.init(master);
    }
    var p = createjs.extend(VideoPublicLeft, createjs.Container);


    // public properties:
    p.version = null;
    p.master = null;
    p.video_Loader = null;
    p.soundLoader = null;
    p.video_is_loaded = false;
    p.music_is_loaded = false;
    p.videoSprite=null;

    // public methods:
    p.init = function (master) {
        //console.log(window.Fotile);
        this.master = master;
        console.log("I'm Public Video Left Player!!!");
        //this.loadMusic();
        this.loadFirsrVideoRes();

    }


    p.loadMusic = function () {
        console.log("加载视频配音");

        /*var assetsPath = "./_assets/video/";
        var sounds = [{
            src:"a.ogg?r="+this.version, data: {
                audioSprite: [
                    {id:"firstduibai", startTime:0, duration:77115.6462585034},
                    //{id:"firstduibai1", startTime:250000, duration:50000},
                    //{id:"firstduibai2", startTime:50000, duration:77115.6462585034},
                    //{id:"firstduibai"},
                ]}
        }
        ];
        //createjs.Sound.alternateExtensions = ["mp3"];
        createjs.Sound.on("fileload", loadSound);
        createjs.Sound.registerSounds(sounds, assetsPath);
        // 加载完成后
        function loadSound(evt){
            console.log("firstduibai")

            //var myInstance = createjs.Sound.play("firstduibai");
            var myInstance = createjs.Sound.play("firstduibai", {startTime: 35000, duration: 10000});
            console.log("getDuration:")
            console.log(myInstance.getDuration())
        }*/







        var video = this;

        // Create a single item to load.
        var assetsPath = "./_assets/video/";
        //var item = {src:assetsPath+"M-GameBG.ogg", id:"music"};
        var manifest = [
            //{id: "firstduibai", src: assetsPath + "a.ogg"},
            //{id: "firstduibai", src: assetsPath + "M-GameBG.mp3"}
            {id: "duibai2", src: assetsPath + "f1.mp3"}
        ]

        // Instantiate a queue.
        soundLoader = new createjs.LoadQueue();
        //createjs.Sound.registerSound("myAudioPath/mySound.ogg", "myID", 3);
        //createjs.Sound.alternateExtensions = ["mp3"];	// add other extensions to try loading if the src file extension is not supported
        soundLoader.installPlugin(createjs.Sound);
        soundLoader.addEventListener("complete", loadComplete);
        soundLoader.addEventListener("fileload", fileComplete);
        soundLoader.addEventListener("error", handleFileError);
        soundLoader.addEventListener("fileprogress", handleFileProgress);
        soundLoader.addEventListener("progress", handleProgress);
        soundLoader.loadManifest(manifest);

        function handleFileError(evt) {
            console.log("error ", evt);
            // An error occurred.
        }
        function handleFileProgress(evt) {
            // Progress happened.
            console.log("Event File Loading: " + (soundLoader.progress.toFixed(2) * 100) + "%");
        }
        function handleProgress(evt) {
            console.log("Event Loading: " + (soundLoader.progress.toFixed(2) * 100) + "%");
            // Progress happened.
        }
        function loadComplete(evt) {
            // Load completed.
            //console.log(evt.target)
            video.music_is_loaded = true;
            console.log("videopublic sounds loaded Complete :)");
            //playSound("firstduibai");

        }
        function fileComplete(evt) {
            console.log("Event Callback file loaded ", evt);
        }
        function playSound(name) {
            // Play the sound using the ID created above.
            //createjs.Sound.muted = master.fotile.switchSound();
            //createjs.Sound.muted = master.fotile.isMute;
            return createjs.Sound.play(name);
        }


    }


    //UI
    p.setupUI = function (){


    }

    //加载视频资源
    p.loadFirsrVideoRes = function (){
        var video = this;
        var manifest = [
            {src:"video/video_l_0.jpg",id:"video_0"},
            {src:"video/video_l_1.jpg",id:"video_1"},
            {src:"video/video_l_2.jpg",id:"video_2"},
            {src:"video/video_l_3.jpg",id:"video_3"},
            {src:"video/video_l_4.jpg",id:"video_4"},
            {src:"video/video_l_5.jpg",id:"video_5"},
            {src:"video/video_l_6.jpg",id:"video_6"},
        ];

        video_Loader = new createjs.LoadQueue(true);
        //animation_Loader.on("error", animationLoaderError);
        video_Loader.on("complete", animationLoadComplete);
        video_Loader.addEventListener("progress", updateLoading);
        video_Loader.loadManifest(manifest, true, "./_assets/");
        //资源加载完毕
        function animationLoadComplete (evt){
            console.log("videopublicleft video loaded!!");
            //console.log(video);
            video.playVideo();
            //setupAnimationUI();

            video.video_is_loaded = true;
            //console.log(video.video_is_loaded);
            //console.log(master.animation_is_loaded)
        };

        function updateLoading(evt){
            video.master.fotile.updateLoading(evt)
        }

    }






    //playvideo
    p.playVideo = function (){

        var total_frames = 1553
        var one_pic_num_max = 250
        var row = 25;
        var colum = 10;
        var pic_w = 302;
        var pic_h = 538;
        var framesArray = [];

        for(var i=0;i<total_frames;i++){
            //console.log( (i % row));
            //console.log((Math.floor((i / one_pic_num_max))));
            var x_offset = pic_w * (i % row);
            var y_offset = pic_h * Math.floor((i % one_pic_num_max) / row);
            var pic_index = Math.floor((i / one_pic_num_max))

            framesArray.push([x_offset,y_offset,pic_w,pic_h,pic_index]);
        }
        var imagesArray = [];
        for(var i=0;i<7;i++){
            imagesArray.push(video_Loader.getResult("video_"+i));
        }
        var runArray = [];
        for(var i=0;i<total_frames;i++){
            runArray.push(i);
        }

        var video_ss = new createjs.SpriteSheet({
            framerate: 24,
            "images": imagesArray,
            frames: framesArray,
               /* [
                // x, y, width, height, imageIndex*, regX*, regY*
                [0, 0, 336, 598,0,0,0],
                [0, 0, 336, 598,0,0,0],

                //[412, 730, 298, 419,0]
            ],*/
            "animations": {
                "run":runArray
                //"run": [0, 1, "run"]
            }
        });
        console.log("play public Video");
        //console.log(framesArray);
        //console.log(imagesArray);
        //console.log(runArray);
        this.videoSprite = new createjs.Sprite(video_ss,'run');
        this.videoSprite.addEventListener("tick",videotick);
        //if(!this.master.playLeftVideo){
        this.videoSprite.stop();
        //}

        var v_w = this.videoSprite.getBounds().width;
        var v_h = this.videoSprite.getBounds().height;
        var w = this.master.fotile.getWidth();
        var h = this.master.fotile.getHeight();
        //var ratio_x = w/v_w;
        var ratio_y = h/v_h;
        var ratio_x =  ratio_y;


        var bg = new createjs.Shape();
        bg.graphics.beginFill("#000000").drawRect(0, 0, w, h);
        this.addChild(bg);
        this.addChild(this.videoSprite);
        this.videoSprite.setTransform(0,0,ratio_x,ratio_y);
        this.videoSprite.x = (w - v_w*ratio_x)/2;
        console.log(this.videoSprite.getBounds())
        //createjs.Sound.play("duibai2");
        //videoSprite = this.videoSprite
        function videotick(evt){
            //console.log(evt.target.currentFrame)
            //if(evt.target.currentFrame == 2){
            //    console.log("播放视频2对白")
            //    createjs.Sound.play("duibai2");
            //}
            if(evt.target.currentFrame>=(total_frames-1)){
                evt.target.stop();
                evt.target.removeEventListener("tick",videotick);
            }
            //videoSprite.stop();
        }



    }

    // add MyApp to myNameSpace
    window.eosi.fotile.VideoPublicLeft = createjs.promote(VideoPublicLeft, "Container");
//}());
}(window));
